import React, { Component } from 'react'
import { Input, MessageBox, Message } from 'element-react'
import Breadcrumb from '../base/Breadcrumb'
import DatePicker from '../../components/base/DatePicker'
import Select from '../base/Select'
import Pagination from '../base/Pagination'
import {withRouter} from 'react-router-dom'
import {formatDate} from '../../common/js/index'
import './discountList.css'

class discountList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      // 总条数
      total: 0,
      pageSize: 10,
      pageNo: 0,
      couponName: '',
      startTime: null,
      endTime: null,
      // 使用下限
      startAmountStart: null,
      // 优惠类型
      discountType: '',
      // 商家
      shops: '',
      // 商品
      goodTypes: '',
      // 标签
      tab: '',
      // 用户类型
      userType: '',
      // 平台
      device: '',
      // 状态
      status: null,
      list: [
        {
          name: 'A001',
          condition: '5000/满减200',
          benginTime: '2018-02-02 13:00:00',
          endTime: '2018-03-03 13:00:00',
          count: 122,
          useAndGet: '12/50',
          status: 1
        }
      ],
      // 优惠类别
      options: [
        {
          label: '打折',
          value: 'discount'
        },
        {
          label: '优惠金额',
          value: 'fullReduction'
        }
      ],
      // 用户
      users: [
        {
          label: 'all',
          value: 1,
        },
        {
          label: '个人',
          value: 2,
        }
      ],
      // 平台
      platform: [
        {
          label: 'pc',
          value: 'pc',
        },
        {
          label: 'Android',
          value: 'Android',
        },
        {
          label: 'IOS',
          value: 'IOS',
        }
      ],
      // 状态
      statu: [
        {
          label: 'Unusable',
          value: '0',
        },
        {
          label: 'Available',
          value: '1',
        }
      ]
    }
  }
  getTime (begin, end) {
    this.setState(
      {
        startTime: new Date(begin).getTime(),
        endTime: new Date(end).getTime()
      }
    )
  }
  selectWay (discountType) {
    this.setState({
      discountType
    })
  }
  selectplatform (device) {
    this.setState({
      device
    })
  }
  selectState (status) {
    this.setState({
      status
    })
  }
  changePage (currentPage) {
    this.setState({
      pageNo: currentPage - 1
    }, () => {
      this.search()
    })
  }
  goEdit (item) {
    this.props.history.push({
      pathname: `/discountEdit/${item.couponTypeId}`,
      state: { fromDashboard: true }
    })
  }
  seeDetail (item) {
    this.props.history.push({
      pathname: `/discountSee/${item.couponTypeId}/see`,
      state: { fromDashboard: true }
    })
  }
  changeStatus (item) {
    console.log(item)
    if (new Date(item.endTime) < new Date()) {
      Message.error('修改失败，超过优惠券有效期')
      return
    }
    MessageBox.confirm('确认修改?', '提示', {
      type: 'warning'
    }).then(() => {
      let typeStatus
      if (item.typeStatus === 1) {
        typeStatus = 0
      } else {
        typeStatus = 1
      }
      this.$ajax.setDiscountState(item.couponTypeId, typeStatus).then(res => {
        if (res.code === 200) {
          Message({
            type: 'success',
            message: '修改成功!'
          })
          this.search()
        }
      })
    }).catch(() => {
      Message({
        type: 'info',
        message: '已取消修改'
      });
    });
  }
  newDiscount () {
    this.props.history.push({
      pathname: '/discountNew',
      state: {formDashBoard: true}
    })
  }
  searchApi (data) {
    this.$ajax.getDiscountList(data).then(res => {
      if (res.code === 200) {
        res.data.content.map(a => {
          a.startTime = formatDate(a.startTime)
          a.endTime = formatDate(a.endTime)
          a.useNum = a.totalNum - a.remainNum
          return a
        })
        console.log(res.data.content)
        this.setState({
          total: Number(res.data.totalElements),
          list: res.data.content
        })
      } else {
        Message.error('搜索失败')
      }
    }).catch(() => {
      Message.error('网络错误')
    })
  }
  // 搜索
  search () {
    let { pageSize, pageNo, couponName, discountType, endTime, goodTypes, shops, startAmountStart, startTime, status, tab, userType} = this.state
    let data = { pageSize, pageNo, couponName, discountType, endTime, goodTypes, shops, startAmountStart, startTime, status, tab, userType}
    this.searchApi(data)
  }
  componentWillMount() {
    this.searchApi({pageNo: 0, pageSize: 10})
  }
  render () {
    return (
      <div className="discountList">
        <Breadcrumb data={['优惠券管理', '优惠券列表']}/>
        <div className="height40"></div>
        <div className="search">
          <div className="search-item">
            <div className="inputGroupList">
              <label className="inputLabelList">名称：</label>
              <Input placeholder="请输入优惠券名称" size="small" className="inputSmall" onChange={value => {this.setState({couponName: value})}}/>
            </div>
            <div className="inputGroupList">
              <label className="inputLabelList">有效时间：</label>
              <DatePicker getTime={this.getTime.bind(this)}/>
            </div>
          </div>
          <div className="search-item">
            <div className="inputGroupList">
              <label className="inputLabelList">适用金额下限：</label>
              <Input placeholder="" size="small" className="inputSmall" onChange={value => {this.setState({startAmountStart: value})}}/>
            </div>
            <div className="inputGroupList">
              <label className="inputLabelList">优惠方式：</label>
              <Select options={this.state.options} select={this.selectWay.bind(this)}/>
            </div>
          </div>
          <div className="search-item">
            <div className="inputGroupList">
              <label className="inputLabelList">商家：</label>
              <Input placeholder="" size="small" className="inputSmall" onChange={shops => {this.setState({shops})}}/>
            </div>
            <div className="inputGroupList">
              <label className="inputLabelList">用户：</label>
              <Input placeholder="" size="small" className="inputSmall" onChange={userType => {this.setState({userType})}}/>
            </div>
            <div className="inputGroupList">
              <label className="inputLabelList">平台：</label>
              <Select options={this.state.platform} select={this.selectplatform.bind(this)}/>
            </div>
          </div>
          <div className="search-item">
            <div className="inputGroupList">
              <label className="inputLabelList">商品：</label>
              <Input placeholder="" size="small" className="inputSmall" onChange={goodTypes => {this.setState({goodTypes})}}/>
            </div>
            <div className="inputGroupList">
              <label className="inputLabelList">标签：</label>
              <Input placeholder="" size="small" className="inputSmall" onChange={tab => {this.setState({tab})}}/>
            </div>
            <div className="inputGroupList">
              <label className="inputLabelList">状态：</label>
              <Select options={this.state.statu} select={this.selectState.bind(this)}/>
            </div>
            <button type="button" className="btn btn-search" onClick={this.search.bind(this)}>搜索</button>
          </div>
          {/* <div className="search-item">
            <div className="inputGroupList">
              <label className="inputLabelList">一级分类：</label>
              <Input placeholder="" size="small" className="inputSmall"/>
            </div>
            <div className="inputGroupList">
              <label className="inputLabelList">二级分类：</label>
              <Input placeholder="" size="small" className="inputSmall"/>
            </div>
            <div className="inputGroupList">
              <label className="inputLabelList">三级分类：</label>
              <Input placeholder="" size="small" className="inputSmall"/>
            </div>
            <button type="button" className="btn btn-search">搜索</button>
          </div> */}
        </div>
        <div><button type="button" className="btn btn-increase" onClick={this.newDiscount.bind(this)}>新增</button></div>
        <table className="table">
          <tbody>
            <tr>
              <th>名称</th>
              <th>适用条件（适用金额下限/优惠方式/优惠数值）</th>
              <th>有效期</th>
              <th>发放总量</th>
              <th>使用/领取</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
            {
              this.state.list.map((a, index) => {
                return (
                  <tr key={index}>
                    <td>{a.typeName}</td>
                    <td>{a.startAmount + ' / ' + a.discountType + ' / ' + a.discountRate}</td>
                    <td>{a.startTime + ' / ' + a.endTime}</td>
                    <td>{a.discountAmount}</td>
                    <td>{a.useNum + ' / ' + a.totalNum}</td>
                    {Number(a.typeStatus) === 1 ? <td>Available</td> : <td>Unusable</td>}
                    <td>
                      <div><button className="btn btn-operate" onClick={this.goEdit.bind(this, a)}>编辑</button></div>
                      <div><button className="btn btn-operate" onClick={this.seeDetail.bind(this, a)}>查看</button></div>
                      <div><button className="btn btn-operate" onClick={this.changeStatus.bind(this, a)}>失效/生效</button></div>
                    </td>
                  </tr>
                )
              })
            }
          </tbody>
        </table>
        <Pagination total={this.state.total} changePage={this.changePage.bind(this)}/>
      </div>
    )
  }
}

export default withRouter(discountList)